package web

import (
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"io"
	"io/fs"
	"net/http"
	"packet_capture/bean"
	process "packet_capture/ps"
	"strconv"
	"sync"
)

var ConnWsGroup = sync.Map{}
var upGrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func StartWeb(webPort int, FS fs.FS) {
	gin.SetMode(gin.ReleaseMode)
	gin.DefaultWriter = io.Discard
	e := gin.Default()
	subStatic, _ := fs.Sub(FS, "static")
	e.StaticFS("/static", http.FS(subStatic))
	e.GET("/process", func(context *gin.Context) {
		info := process.GetAllProcessInfo()
		context.JSON(200, info)
	})
	e.GET("/process/openFiles", func(context *gin.Context) {
		query := context.Query("pid")
		atoi, _ := strconv.Atoi(query)
		context.JSON(200, process.GetFileInfo(int32(atoi)))
	})
	e.GET("/process/openNet", func(context *gin.Context) {
		query := context.Query("pid")
		atoi, _ := strconv.Atoi(query)
		context.JSON(200, process.GetNetInfo(int32(atoi)))
	})
	e.GET("/ws", ws)
	if webPort <= 0 {
		webPort = 8080
	}
	e.Run(":" + strconv.Itoa(webPort))
}

func WsSend(data bean.Data) {
	ConnWsGroup.Range(func(key, value interface{}) bool {
		WS := key.(*websocket.Conn)
		err := WS.WriteJSON(data)
		if err != nil {
			return false
		}
		return true
	})
}

func ws(c *gin.Context) {
	//升级get请求为webSocket协议
	ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		return
	}
	ConnWsGroup.Store(ws, nil)
	defer func() {
		ConnWsGroup.Delete(ws)
		ws.Close()
	}()
	for {
		//读取ws中的数据
		mt, message, err := ws.ReadMessage()
		if err != nil {
			break
		}
		if string(message) == "ping" {
			message = []byte("pong")
		}
		//写入ws数据
		err = ws.WriteMessage(mt, message)
		if err != nil {
			break
		}
	}
}
